<script lang="ts" setup>
import { computed, defineAsyncComponent, ref } from 'vue'
import {
  lockStatus,
  bikeOnlineStatus,
  allowChangeBattery,
  formatterIsHasBattery,
  formatterLuggageStatus,
  formatterPower
} from '@/utils/formatter'
import {
  RentBikeTablePageType,
  BikeType,
  FeeRulesType,
  OnlineStatus,
  MaskStatusType
} from '@/types/enum'
import { useRouter } from 'vue-router'
import { queryBikeTableCol, queryShortBikeCol } from '@/api/bike/types/bike'
import {
  lockShortTermBike,
  unMaintenanceShortTermBike,
  forceReturnBike,
  refreshShortTermBikeLocation,
  maintenanceShortTermBike,
  addOrderRemark,
  queryOrderRemark,
  openMask
} from '@/api/bike'
import { copyEvent } from '@/utils'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage, ElMessageBox } from 'element-plus'

const TieredBillingInfo = defineAsyncComponent(
  () => import('@/components/popover/TieredBillingInfo.vue')
)
const PackageInfo = defineAsyncComponent(() => import('@/components/popover/PackageInfo.vue'))
const BikeInfoDialog = defineAsyncComponent(() => import('@/components/dialog/BikeInfo.vue'))
const BikeInfoDialogRef = ref<InstanceType<typeof BikeInfoDialog> | null>(null)
const router = useRouter()
interface Props {
  data: Array<any>
  type: BikeType
  page: RentBikeTablePageType
  loading: boolean
  isInOperatorsInfo: boolean
  isSearchStore?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  isSearchStore: false
})
const isLongRent = computed(() => {
  return props.page === 'longRent'
})
const isTimeRent = computed(() => {
  return props.page === 'timeRent'
})
const changeMaskStatus = computed(() => {
  return (maskStatus: MaskStatusType) => {
    switch (maskStatus) {
      case '0':
        return '头盔已归还'
      case '1':
        return '头盔未归还'
      default:
        return ''
    }
  }
})
const emits = defineEmits([
  'show-battery-size',
  'show-orderinfo',
  'nomal-return-car',
  'force-return-car',
  'refresh'
])
/** 查看故障记录 */
const seeFaultRecord = (row: queryBikeTableCol) => {
  router.push({
    name: 'FaultRecord',
    query: {
      bikeCode: row.bikeCode,
      bikeId: row.bikeId
    }
  })
}
/** 查看车辆位置 */
const seeBikeLocation = (row: any) => {
  if (isLongRent.value) {
    router.push({
      name: 'LongBikeLocation',
      query: {
        longtitude: row.longtitude,
        latitude: row.latitude,
        bikeCode: row.bikeCode
      }
    })
  } else {
    router.push({
      name: 'TimeBikeLocation',
      query: {
        bikeId: row.bikeId,
        storeId: props.isInOperatorsInfo ? row.storeData.storeId : undefined
      }
    })
  }
}
/** 查看租赁记录 */
const seeRentRecord = (row: any) => {
  router.push({
    name: 'RentRecord',
    query: {
      bikeCode: row.bikeCode,
      bikeId: row.bikeId
    }
  })
}
/** 查看订单详情 */
const seeOrderInfo = (row: queryBikeTableCol) => {
  emits('show-orderinfo', row.orderId, row.userId)
}
/** 计费规则 */
const changeProductType = computed(() => {
  return (productType: FeeRulesType) => {
    switch (productType) {
      case 'TimeBased':
        return '按时长计费'
      case 'Tiered':
        return '按阶梯计费'
      default:
        return ''
    }
  }
})
/** 常规还车 */
const NomalReturnCar = (row: any) => {
  emits('nomal-return-car', row.bikeId)
}
/** 强制还车 */
const ForceReturnCar = async (row: any) => {
  try {
    const res = await forceReturnBike({
      token: getToken() ?? '',
      bikeId: row.bikeId
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
    }
  } catch (error) {
    console.error(error)
  }
}
/**关锁 */
const closeTheLock = async (row: any) => {
  try {
    const res = await lockShortTermBike({
      token: getToken() ?? '',
      bikeId: row.bikeId
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
    }
    emits('refresh')
  } catch (error) {
    console.error(error)
    emits('refresh')
  }
}
/** 解除维修 */
const releaseMaintenance = async (row: any) => {
  try {
    const res = await unMaintenanceShortTermBike({
      token: getToken() ?? '',
      bikeId: row.bikeId
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
    }
    emits('refresh')
  } catch (error) {
    console.error(error)
    emits('refresh')
  }
}
/** 拉入维修 */
const Maintenance = async (row: any) => {
  ElMessageBox.confirm('车辆拉入维修后，用户无法正常使用，是否拉入维修', '拉入维修', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      const res = await maintenanceShortTermBike({
        token: getToken() ?? '',
        bikeId: row.bikeId
      })
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
      }
      emits('refresh')
    } catch (error) {
      console.error(error)
      emits('refresh')
    }
  })
}
/** 查看历史行程 */
const seeHistoryLocus = (row: any) => {
  router.push({
    name: 'BikeHistoryList',
    query: {
      bikeCode: row.bikeCode,
      phone: row.phone
    }
  })
}
/** 查看车辆信息 */
const openBikeInfoDialog = (row: any) => {
  BikeInfoDialogRef.value?.setId(row.bikeId)
  BikeInfoDialogRef.value?.open()
}
const showMoreInfo = (row: queryShortBikeCol) => {
  router.push({
    name: 'UserInfo',
    query: {
      userId: row.userId,
      phone: row.phone,
      selectType: 'charge'
    }
  })
}
/** 刷新车辆定位 */
const refresh = async (row: queryShortBikeCol) => {
  const res = await refreshShortTermBikeLocation({
    token: getToken() ?? '',
    bikeId: row.bikeId
  })
  if (res.statusCode === '0') {
    ElMessage.success({
      plain: true,
      message: res.data
    })
  } else {
    ElMessage.error({
      plain: true,
      message: res.data
    })
  }
}
/** 增加备注 */
const RemarkDialog = defineAsyncComponent(
  () => import('@/components/basic/BasicTextAreaDialog.vue')
)
const RemarkDialogRef = ref<InstanceType<typeof RemarkDialog> | null>(null)
const remark = (row: queryShortBikeCol) => {
  RemarkDialogRef.value?.setId(row.orderId!, '备注')
  RemarkDialogRef.value?.open()
}
const handleSubmitRemark = async (id: string, content: string) => {
  try {
    const res = await addOrderRemark({
      token: getToken() ?? '',
      orderId: id,
      content: content
    })
    if (res.statusCode === '0') {
      ElMessage.success({
        plain: true,
        message: res.data
      })
      emits('refresh')
      RemarkDialogRef.value?.close()
    }
  } catch (error) {
    console.error(error)
  }
}
/** 查看备注 */
const RemarkLogDialog = defineAsyncComponent(() => import('@/components/basic/BasicStepDialog.vue'))
const RemarkLogDialogRef = ref<InstanceType<typeof RemarkLogDialog> | null>(null)
const openRemarkInfo = (row: queryShortBikeCol) => {
  RemarkLogDialogRef.value?.setData(row.orderId!, '备注', getStepData)
  RemarkLogDialogRef.value?.open()
}
const getStepData = async (orderId: string) => {
  try {
    const res = await queryOrderRemark({
      token: getToken() ?? '',
      orderId: orderId
    })
    if (res.statusCode === '0') {
      return res.data
    } else {
      return []
    }
  } catch (error) {
    console.error(error)
    return []
  }
}

const handleOpenMask = async (row: queryShortBikeCol) => {
  try {
    const res = await openMask({
      token: getToken() ?? '',
      bikeId: row.bikeId
    })
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
      emits('refresh')
    }
  } catch (error) {
    console.error(error)
  }
}
</script>

<template>
  <el-table :data="props.data" v-loading="loading" align="center" class="no-border">
    <el-table-column
      prop="orderId"
      :label="page === 'longRent' ? '订单编号' : '行程编号'"
      min-width="230"
      v-if="type === '3'"
      fixed="left"
    >
      <template #default="scope">
        <div flex items-center>
          <span whitespace-normal break-all>{{ scope.row.orderId }}</span
          >&nbsp;&nbsp;&nbsp;
          <span @click="copyEvent(scope.row.orderId)" class="is-reference" v-if="scope.row.orderId"
            >复制</span
          >
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="bikeCode" label="车辆编号" min-width="120" fixed="left" align="center" />
    <template v-if="type === '3'">
      <el-table-column prop="phone" label="手机号" min-width="120">
        <template #default="scope">
          <el-popover v-if="scope.row.rentCardName">
            <span>{{ scope.row.rentCardName }}</span>
            <template #reference>
              <div
                cursor-pointer
                hover:underline
                hover:decoration-primary
                hover:decoration-1
                hover:decoration-solid
                @dblclick="showMoreInfo(scope.row)"
              >
                <span hover:color-primary-light>{{ scope.row.phone }} </span>
              </div>
            </template>
          </el-popover>
          <div
            v-else
            cursor-pointer
            hover:underline
            hover:decoration-primary
            hover:decoration-1
            hover:decoration-solid
            @dblclick="showMoreInfo(scope.row)"
          >
            <span hover:color-primary-light>{{ scope.row.phone }} </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" show-overflow-tooltip min-width="150" />
      <el-table-column prop="usedTime" label="时长(分)" min-width="80" align="center" />
    </template>
    <el-table-column
      prop="storeData.storeName"
      label="所属门店"
      align="center"
      min-width="150"
      v-if="isTimeRent && !isSearchStore"
    />
    <el-table-column prop="bikeStatus" label="车辆状态" align="center" />
    <el-table-column prop="lockStatus" label="车锁状态" align="center" :formatter="lockStatus" />
    <el-table-column
      prop="bikeOnlineStatus"
      label="网络状态"
      align="center"
      :formatter="bikeOnlineStatus"
    />
    <el-table-column
      prop="powerLevel"
      label="车辆电量"
      :formatter="formatterPower"
      align="center"
    />
    <el-table-column
      prop="maskStatus"
      label="头盔状态"
      align="center"
      v-if="isTimeRent"
      min-width="120"
    >
      <template #default="scope">
        <span
          :style="{
            color:
              scope.row.maskStatus === '0' ? 'var(--xy-success-color)' : 'var(--xy-warning-color)'
          }"
        >
          {{ changeMaskStatus(scope.row.maskStatus) }}
        </span>
      </template>
    </el-table-column>
    <el-table-column
      prop="hasBattery"
      label="电池状态"
      min-width="130"
      v-if="isTimeRent"
      align="center"
      :formatter="formatterIsHasBattery"
    />
    <el-table-column
      prop="luggageStatus"
      label="电池仓状态"
      min-width="120"
      align="center"
      v-if="isTimeRent"
      :formatter="formatterLuggageStatus"
    />
    <el-table-column prop="inputVoltage" label="电压" align="center" />
    <el-table-column
      prop="allowChangeBattery"
      label="免费换电"
      min-width="100"
      align="center"
      :formatter="allowChangeBattery"
      v-if="isTimeRent"
    />
    <el-table-column label="所属套餐" align="center" min-width="200" v-if="isLongRent">
      <template #default="scope">
        <el-popover
          trigger="click"
          popper-class="package-info_popover"
          v-if="scope.row.productData"
          min-width="auto"
        >
          <package-info :data="scope.row" />
          <template #reference>
            <el-button class="is-show" link type="primary">{{
              scope.row.productData.name
            }}</el-button>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="故障记录" align="center" v-if="isLongRent">
      <template #default="scope">
        <el-button class="is-show" link type="primary" @click="seeFaultRecord(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="车辆位置" align="center" fixed="right">
      <template #default="scope">
        <el-button class="is-show" link type="primary" @click="seeBikeLocation(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="历史行程" align="center" fixed="right" v-if="isTimeRent">
      <template #default="scope">
        <el-button class="is-show" link type="primary" @click="seeHistoryLocus(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="车辆信息" align="center" fixed="right" v-if="isTimeRent">
      <template #default="scope">
        <el-button class="is-show" link type="primary" @click="openBikeInfoDialog(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="订单详情" align="center" v-if="isLongRent && type == '3'">
      <template #default="scope">
        <el-button class="is-show" link type="primary" @click="seeOrderInfo(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column
      label="计费规则"
      align="center"
      prop="feeRules"
      v-if="isTimeRent"
      min-width="130"
    >
      <template #default="scope">
        <el-popover
          placement="bottom"
          trigger="hover"
          popper-class="tiered-billing-popover"
          width="auto"
        >
          <template #reference>
            <span class="cursor-pointer is-reference">{{
              changeProductType(scope.row.productType)
            }}</span>
          </template>
          <template #default>
            <tiered-billing-info
              :title="changeProductType(scope.row.productType)"
              :data="scope.row.feeRules"
            />
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="租赁记录" align="center" v-if="isLongRent" fixed="right">
      <template #default="scope">
        <el-button class="is-show" link type="primary" @click="seeRentRecord(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="备注信息" align="center" fixed="right">
      <template #default="scope">
        <el-button
          class="is-show"
          v-if="isTimeRent && scope.row.bikeStatus == '使用中'"
          link
          type="primary"
          @click="openRemarkInfo(scope.row)"
          >查看</el-button
        >
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" min-width="450px" align="center">
      <template #default="scope">
        <div flex items-start>
          <template v-if="scope.row.bikeStatus == '使用中' && isTimeRent">
            <el-button link type="primary" @click="remark(scope.row)">备注</el-button>
            <div flex flex-col ml-5 justify-center>
              <el-button
                link
                type="primary"
                @click="NomalReturnCar(scope.row)"
                :disabled="scope.row.bikeOnlineStatus === OnlineStatus.UnOnLine"
                >常规还车</el-button
              >
              <span class="text-[10px] text-[#999999]" leading-none>(需校验)</span>
            </div>
            <div flex flex-col justify-center>
              <el-button
                link
                type="primary"
                @click="ForceReturnCar(scope.row)"
                :disabled="scope.row.bikeOnlineStatus === OnlineStatus.UnOnLine"
                >强制还车</el-button
              >
              <span class="text-[10px] text-[#999999]" leading-none>(无需校验)</span>
            </div>
            <el-button link type="primary" @click="refresh(scope.row)">刷新位置</el-button>
            <el-button link type="primary" @click="handleOpenMask(scope.row)">开头盔锁</el-button>
          </template>
          <el-button
            link
            type="primary"
            v-if="scope.row.lockStatus == '0' && isTimeRent"
            @click="closeTheLock(scope.row)"
            >关锁</el-button
          >
          <el-button
            link
            type="primary"
            @click="releaseMaintenance(scope.row)"
            v-if="scope.row.bikeStatus == '维修中' && isTimeRent"
            >解除维修</el-button
          >
          <el-button link type="primary" @click="Maintenance(scope.row)" v-if="isTimeRent"
            >拉入维修</el-button
          >
        </div>
      </template>
    </el-table-column>
  </el-table>
  <bike-info-dialog ref="BikeInfoDialogRef" />
  <remark-dialog ref="RemarkDialogRef" @submit="handleSubmitRemark" />
  <remark-log-dialog ref="RemarkLogDialogRef" type="remark" @submit="handleSubmitRemark" />
</template>

<style scoped>
.package-info_popover,
.store-info_popover {
  padding: 0px;
}
</style>
